package com.lhczf.lucenedb.util;

import com.lhczf.lucenedb.service.DataHub;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FileUtils {

    private FileUtils() {
    }

    public static void createDir(String dataDir) {
        File monitorPath = new File(dataDir);
        if (!monitorPath.exists() || !monitorPath.isDirectory()) {
            log.warn("目录不存在，或者不是一个目录。重新创建目录：" + monitorPath.getAbsolutePath());
            monitorPath.mkdirs();
        }
    }

    public static void deleteFile(File dataFile) {
        try {
            Files.delete(Paths.get(dataFile.getAbsolutePath()));
        } catch (IOException e) {
            log.error("无法自动删除文件：{}。", dataFile.getAbsolutePath());
        }
    }

    public static List<File> findDirs(File dataDir) {
        List<File> dirs = new ArrayList<>();
        File[] files = dataDir.listFiles();
        if (files == null) return dirs;
        for (File file : files) {
            if (file.isDirectory()) {
                dirs.add(file);
            }
        }
        return dirs;
    }

    public static void dealOldFiles(File dataDir) {
        File[] files = dataDir.listFiles();
        if (files == null) return;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isFile()) {
                DataHub.dataQueue.offer(file.getAbsolutePath());
            } else {
                dealOldFiles(file);
            }
        }
    }
}
